package com.taoye.thread;

public class Demo26 {
	public static void main(String[] args) throws InterruptedException {
		Demo26Service service = new Demo26Service();
		Thread t = new Demo26ThreadA(service);
		t.setName("A");
		t.start();
		Thread t2 = new Demo26ThreadB(service);
		t2.setName("B");
		t2.start();
		Thread.sleep(8000);
		long start = Utils.start1 < Utils.start2 ? Utils.start1 : Utils.start2;
		long end = Utils.end1 > Utils.end2 ? Utils.end1 : Utils.end2;
		System.out.println("全部线程完成总耗时：" + (end - start) + "毫秒");
		System.out.println("number的值为：" + service.getNumber());
	}
}

class Demo26Service {
	private int number = 0;

	/**
	 * 这里是模拟业务逻辑
	 */
	public synchronized void addNumber() {
		try {
			System.out.println(Thread.currentThread().getName() + "线程开始操作了");
			// 模拟需要同步的耗时操作，因为不同步number的值会造成脏读
			for (int i = 0; i < 20; i++) {
				Thread.sleep(50);
				number += 10;
			}
			System.out.println(Thread.currentThread().getName() + "线程操作完了：值为：" + number);
			// 这是模拟另外一些不需要同步的耗时操作
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public int getNumber() {
		return number;
	}
}

class Demo26ThreadA extends Thread {
	private Demo26Service service;

	public Demo26ThreadA(Demo26Service service) {
		this.service = service;
	}

	@Override
	public void run() {
		Utils.start1 = System.currentTimeMillis();
		service.addNumber();
		Utils.end1 = System.currentTimeMillis();
	}
}

class Demo26ThreadB extends Thread {
	private Demo26Service service;

	public Demo26ThreadB(Demo26Service service) {
		this.service = service;
	}

	@Override
	public void run() {
		Utils.start2 = System.currentTimeMillis();
		service.addNumber();
		Utils.end2 = System.currentTimeMillis();
	}
}
